package cn.com.dashihui.web.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.ExcelExportUtil.Pair;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.AdSeller;
import cn.com.dashihui.web.dao.GSR;
import cn.com.dashihui.web.dao.Seller;
import cn.com.dashihui.web.dao.Store;
import cn.com.dashihui.web.dao.SysConfig;
import cn.com.dashihui.web.dao.User;
import cn.com.dashihui.web.service.StoreService;

@RequiresAuthentication
public class StoreController extends BaseController{
	private StoreService storeService = new StoreService();
    
	//@RequiresPermissions("dict:store:index")
    public void index(){
    	List<Record> list=storeService.findAllSeller();
    	setAttr("list", list);
        render("index.jsp");
    }
    
    /**
     * 查看分公司详情
     */
    public void detail(){
    	String storeid=getPara("storeid");
		if(storeid!=null){
			setAttr("object", storeService.detail(storeid));
		}
		render("detail.jsp");
    }
    /**
     * 驳回doCancel
     */
    public void doCancel(){
    	String storeid=getPara("storeid");
    	String reason=getPara("reason");
    	String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
    	if(StrKit.isBlank(storeid)){
			renderFailed("参数storeid不能为空");
    		return;
    	}else{
    		int i= storeService.doCancel(reason,storeid,checktime);
    		if(i==1){
    			renderSuccess(storeService.findByStoreid(storeid));
    			return ;
    		}else{
    			//3.其他情况
				renderFailed("驳回失败");
				return;
    		}
    	}
    }
     /**
     * 驳回doCancel
     */
    public void toCancel(){
    	String storeid=getPara("storeid");
    	if(StrKit.isBlank(storeid)){
			renderFailed("参数storeid不能为空");
    		return;
    	}else{
    		setAttr("storeid", storeid);
    		render("doCancel.jsp"); 
    	}
    }
    /**
     * 通过审核
     */
    public void doAccept(){
    	String storeid=getPara("storeid");
    	System.out.println(storeid);
    	String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
    	if(StrKit.isBlank(storeid)){
			renderFailed("参数storeid不能为空");
    		return;
    	}else{
    			//获取当前的store
    			Store store = storeService.findStore(storeid);
    			//获取当前注册用户所需的参数
    			
				//电话
    			String aphone = store.get("aphone");
    			int sstate = store.getInt("state");
    			//通过电话号码查询当前用户对象，即验证是否存在账号
    			if (sstate!=6) {
    				User userNew = storeService.getUserByPhone(aphone);
        			//判断是否存在
        			if (userNew!=null) {
    					//此手机号已存在，无法审核
    					renderResult(1);
    					return;
    				}else{
    					//设置用户密码，默认为手机号后六位
    					String password = aphone.substring(aphone.length() - 6);
    					//获取对应的sellerId
    	    			String sellerId  = store.get("sellerId");
    	    			int stid  = store.get("id");
    	    			//查询对应的sellername
    	    			Seller seller = storeService.findSeller(sellerId);
    	    			int inviteid = seller.getInt("tokerUserid");
    	    			int seid  = seller.get("id");
    					//审核通过
    		    		seller.set("checktime", checktime).set("state", 2);
    					User user2 = new User();
    					String date= DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
    					//所属分公司
    	    			String aname = store.get("aname");
    	    			String busLicense = store.get("busLicense");
    	    			//会员状态
    	    			int state =1;
    	    			//会员地址
    	    			String address  = store.get("address");
    	    			String cards=DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS");
    	    			String card=cards.substring(2);
    					user2.set("name", aname)
    						.set("card", card)
    					 	.set("phone", aphone)
    					 	.set("state", state)
    					 	.set("address", address)
    					 	.set("cardIdNo", busLicense)
    					 	.set("createDate", date)
    					 	.set("babythday",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
    					 	.set("taici", SysConfig.tBusUserTaici.level_6)
    					 	.set("toBossTwoId", stid)
    					 	.set("toBossThreeId", seid)
    					 	.set("inviteid", inviteid)
    					 	.set("userType", 1)//设置客户类型为法人
    					 	.set("password", CommonKit.encryptPassword(password));//设置用户密码，默认为手机号后六位
    					AdSeller newStore = new AdSeller();
    					newStore.set("username", aphone)
    							.set("password", new DefaultPasswordService().encryptPassword(password))
    							.set("trueName", aname)
    							.set("phonenumber", aphone)
    							.set("storeid", storeid)
    							.set("enabled", 1)
    							.set("VipPower", 0);
    					//事务
    					boolean flag = Db.tx(new IAtom() {
    				           @Override
    				           public boolean run() throws SQLException {
    				            return (storeService.doAccept(storeid,checktime)==1)&&user2.save();
    				           }
    				          });
    					 if (flag) {
    						 int tokerid = user2.get("id");
    						 store.set("tokerUserid", tokerid);
    						 newStore.set("tokerUserid", tokerid);

    						 boolean flag1 = Db.tx(new IAtom() {
      				           @Override
      				           public boolean run() throws SQLException {
      				            return newStore.save()&&store.update();
      				           }
      				          });
    						 if (flag1) {
    							 int adSellerId = newStore.getInt("id");
 								 storeService.addRolesDj(adSellerId);
    							 renderSuccess();
							}
    					} else {
    						logger.error("前端用户添加失败！");
    					}
    				}
        			renderSuccess(storeService.findByStoreid(storeid));
        			return ;
				} else {
					storeService.doAccept(storeid,checktime);
				}
    			renderSuccess(storeService.findByStoreid(storeid));
    			return ;
    	}
    }
    
    /**
     * 分页数据
     */
    public void page(){
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		String sellerId = getPara("sellerId");
		String sId = getPara("sId");
		//上线时间
		String beginDate = getPara("beginDate");
		String endDate = getPara("endDate");
		//状态
		int state = getParaToInt("state",0);
		renderResult(0,storeService.findByPage(pageNum, pageSize, sellerId,beginDate,endDate,state, sId));
	}

	/**
	 * 增加页面
	 */
	public void toAdd(){
		render("add.jsp");
	}
	
	
	 /**
	  * 编辑分公司
	  */
		public void toEdit(){
			String storeid = getPara("storeid");
			if(!StrKit.isBlank(storeid)){
				setAttr("object", storeService.findById(storeid));
			}
			render("edit.jsp");
		}
		/**
		 * 分公司图的添加图片的页面
		 */
		public void imageIndex(){
			String stroeimagenum =getPara(0);
			setAttr("stroeimagenum",stroeimagenum);
	        render("storeimageList.jsp");
	    }	
		/**
		 * 图片分页
		 */
	    public void imagePage(){
	    	String stroeimagenum =getPara(0);		
	    	renderSuccess(storeService.findAllImages(stroeimagenum));
	    }
	/**
	 * excel导出
	 */
	public void doExcel(){
		List<Pair> titles = new ArrayList<Pair>();
		titles.add(new Pair("storeid", "分公司ID"));
	    titles.add(new Pair("title", "分公司名称"));
	    titles.add(new Pair("scope", "主营范围"));
	    titles.add(new Pair("sellerName", "所属公司"));
	    titles.add(new Pair("aname", "分公司联系人"));
	    titles.add(new Pair("createtime", "创建时间 "));
	    titles.add(new Pair("starttime", "申请时间 "));
	    
	    titles.add(new Pair("aphone", "联系方式"));
	    titles.add(new Pair("state", "状态"));
	    titles.add(new Pair("checktime", "审核时间 "));
	    String sellerId = getPara("sellerId");
		String sId = getPara("sId");
		//上线时间
		String beginDate = getPara("beginDate");
		String endDate = getPara("endDate");
		//状态
		int state = getParaToInt("state",0);
		List<Record> list=storeService.findExcelByPage(sellerId,sId,beginDate,endDate,state);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			Record record=new Record();
			record.set("storeid",list.get(i).get("storeid"));
			record.set("title", list.get(i).get("title"));
			if(list.get(i).get("scope").equals(1)){
				record.set("scope", "常规");
			}else if(list.get(i).get("scope").equals(2)){
				record.set("scope", "团购");
			}else if(list.get(i).get("scope").equals(3)){
				record.set("scope", "常规+团购");
			}
			record.set("sellerName", list.get(i).get("sellerName"));
			record.set("createtime", list.get(i).get("createtime"));
			record.set("starttime", list.get(i).get("starttime"));
			record.set("aname", list.get(i).get("aname"));
			record.set("aphone", list.get(i).get("aphone"));
			if(list.get(i).get("state").equals(1)){
				record.set("state", "上线审核中");
			}else if(list.get(i).get("state").equals(2)){
				record.set("state", "上线");
			}else if (list.get(i).get("state").equals(3)){
				record.set("state", "下线");
			}
			record.set("checktime", list.get(i).get("checktime"));
			listz.add(record);
 		}
		// 导出
		storeService.export(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
	/**
	 * 下线分公司
	 */
	public void doDown(){
		String storeid=getPara("storeid");
    	System.out.println(storeid);
    	String downtime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
    	if(StrKit.isBlank(storeid)){
			renderFailed("参数storeid不能为空");
    		return;
    	}else{
    		List<GSR> listGSR = storeService.finds(storeid);
			if (listGSR!=null&&listGSR.size()>0) {
				for (GSR gsr : listGSR) {
					String goodstore = gsr.get("goodstore");
					System.out.println("下线对应的分公司下的商品");
					//下线对应的分公司下的商品
					int downGoods = storeService.downGoods(goodstore);
					System.out.println("下线对应的分公司下的商品"+downGoods);
				}
			}
			System.out.println("下线对应的分公司");
			//下线对应的分公司
			storeService.downStore(downtime,storeid);
			renderSuccess();
    	}
	}
}
